package com.sjp.myspring.web.servlet;

import com.sjp.myspring.utils.StringUtils;

import java.io.File;
import java.util.Locale;

public class JPViewResolver {

    private final String DEFAULT_TEMPLATE_SUFFIX = ".html";
    private File templateRootDir;

    public JPViewResolver(String templateRoot) {
        String templateRootPath = this.getClass().getClassLoader().getResource(templateRoot).getFile();
        templateRootDir = new File(templateRootPath);

    }

    public JPView resolveViewName(String viewName, Locale locale) {
        if (StringUtils.isEmpty(viewName)) {
            return null;
        }
        viewName = viewName.endsWith(DEFAULT_TEMPLATE_SUFFIX) ? viewName : viewName + DEFAULT_TEMPLATE_SUFFIX;
        File templateFile = new File((templateRootDir.getPath() + "/" + viewName).replaceAll("/+", ""));
        return new JPView(templateFile);
    }
}
